package com.funny.stock.base.redis;

import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author pengl
 * @date 2020/7/30
 */
@Component
public class RestTemplateTool {
    private static final Logger logger = LoggerFactory.getLogger(RestTemplateTool.class);

    @Autowired
    private RestTemplate restTemplate;


    public <T> T getForObject(String url, Class<T> responseType){
        try {
            return getForObject(url,responseType,null);
        }catch (Exception e){
            logger.error("getForObject error:{}",e.getMessage());
        }
        return null;
    }

    public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables){
        try {
            return restTemplate.getForObject(url,responseType,uriVariables == null ? new HashMap<>() : uriVariables);
        }catch (Exception exception){
            logger.error("getForObject error:{}",exception.getMessage());
        }
        return null;
    }

    public <T> T postForObject(String url, Object dataObject, Class<T> responseType){
        try {
            return restTemplate.postForObject(url, dataObject, responseType);
        } catch (Exception e){
            logger.error("postForObject error:{}",e.getMessage());
        }
        return null;
    }

    public <T> T postJsonForObject(String url,Object dataObject, Class<T> responseType){
        return postJsonForObject(url,dataObject,responseType,null);
    }

    public <T> T postJsonForObject(String url,Object dataObject, Class<T> responseType,List<String> cookieList){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String content = JSONObject.toJSONString(dataObject);
        if(cookieList != null){
            headers.put("Cookie", cookieList);
        }
        HttpEntity<String> httpRequest = new HttpEntity<>(content, headers);

        try {
            return restTemplate.postForObject(url, httpRequest, responseType);
        }catch (Exception exception){
            logger.error("postJsonForObject error:{}",exception.getMessage());
        }

        return null;
    }




}
